﻿/// <reference path="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"/>
/// <reference path="SP.js"/>

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

Function.method('curry', function () {
    var slice = Array.prototype.slice,
		args = slice.apply(arguments),
		that = this;
    return function () {
        return that.apply(null, args.concat(slice.apply(arguments)));
    };
});

if (typeof iSharePoint == 'undefined' || !Bain)
	iSharePoint = {};

if (typeof iSharePoint.WebPartManager == 'undefined' || !iSharePoint.WebPartManager)
    iSharePoint.WebPartManager = (function () {
        //Private Members
        //Public Members
        return {
            doInit: function () {
                $("#mis-wpg tr").draggable({
                    connectToSortable: "div.mis-wpZone > table > tbody",
                    helper: "clone",
                    revert: "invalid",
                    start: function (event, ui) {
                        ui.helper.addClass('mis-wpg-wpTile');
                    },
                    stop: function (event, ui) {
                        $('div.mis-wpZone > table > tbody').sortable('refresh');
                    }
                }).disableSelection();

                $("div.mis-wpZone > table > tbody").sortable(iSharePoint.WebPartManager.createSortableSettings());
                $("tr", $("div.mis-wpZone tbody"))
				    .find(".ms-WPHeader")
				    .css({ cursor: 'move' });
            },
            doDestroy: function (group) {
                $("div.mis-wpZone > table > tbody").sortable('destroy');
            },

            addWebPart: function (parent, webPart, zoneId, elementIndex) {
                var clientContext = new SP.ClientContext.get_current();
                var pageUrl = '/Pages/home.aspx' /*WPSC.WebPartPage.WebURL*/;
                var page = clientContext.get_web().getFileByServerRelativeUrl(pageUrl);
                var limitedWebPartManager = page.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.user);

                //decode xml
                var webPartXml = webPart.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
                var webPartDefinition = limitedWebPartManager.importWebPart(webPartXml);
                var insertWebPart = webPartDefinition.get_webPart();

                var OnAddCompleted = this.onWebPartAddCompleted.curry(zoneId, parent);

                //var addToZone = this.addWebPartToZone.curry(OnAddCompleted, limitedWebPartManager, insertWebPart, zoneId);
                // Get GUID for part after zoneIndex
                //if ( parent.children.length != 1 ) {
                //    this.getZoneIndex(limitedWebPartManager, parent, elementIndex, addToZone);
                //} else {
                //addToZone( 0 );
                limitedWebPartManager.addWebPart(insertWebPart, zoneId, 0);
                clientContext.executeQueryAsync(OnAddCompleted, this.onClientQueryFailed);
                //}
            },

            moveWebPart: function (parent, webPartId, zoneId, elementIndex) {
                var clientContext = new SP.ClientContext.get_current();
                var pageUrl = '/Pages/home.aspx' /*WPSC.WebPartPage.WebURL*/;
                var page = clientContext.get_web().getFileByServerRelativeUrl(pageUrl);
                var limitedWebPartManager = page.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.user);

                var moveToZoneIndex = this.moveWebPartToZoneIndex.curry(limitedWebPartManager, webPartId, zoneId);

                this.getZoneIndex(limitedWebPartManager, $(parent), elementIndex, moveToZoneIndex);
            },

            getZoneIndex: function (limitedWebPartManager, parent, elementIndex, onCompleted) {
                var clientContext = new SP.ClientContext.get_current();

                var insertBefore = parent.children()[elementIndex + 1];
                var insertBeforeOffset = 0;
                if (insertBefore == undefined) {
                    insertBefore = parent.children()[elementIndex - 1];
                    insertBeforeOffset = 1;
                }
                var insertBeforeId = $("div.ms-WPBody", $(insertBefore)).attr("WebPartID");

                var webParts = limitedWebPartManager.get_webParts();
                clientContext.load(webParts);
                clientContext.executeQueryAsync(function (sender, args) {

                    var insertBeforeDef = webParts.getById(insertBeforeId);
                    var insertBeforePart = insertBeforeDef.get_webPart();

                    clientContext.load(insertBeforePart, 'ZoneIndex');
                    clientContext.executeQueryAsync(function (sender, args) {
                        var insertBeforeZoneIndex = insertBeforePart.get_zoneIndex() + insertBeforeOffset;
                        onCompleted(insertBeforeZoneIndex);
                    }, this.onClientQueryFailed);
                }, this.onClientQueryFailed);
            },

            addWebPartToZone: function (onWebPartAddCompleted, limitedWebPartManager, webPart, zoneId, zoneIndex) {
                var clientContext = new SP.ClientContext.get_current();
                limitedWebPartManager.addWebPart(webPart, zoneId, zoneIndex);
                clientContext.executeQueryAsync(onWebPartAddCompleted, this.onClientQueryFailed);
            },

            moveWebPartToZoneIndex: function (limitedWebPartManager, webPartId, zoneId, zoneIndex) {
                var clientContext = new SP.ClientContext.get_current();
                var webParts = limitedWebPartManager.get_webParts();
                clientContext.load(webParts);
                clientContext.executeQueryAsync(function (sender, args) {

                    var webPartDef = webParts.getById(webPartId);
                    webPartDef.moveWebPartTo(zoneId, zoneIndex);
                    webPartDef.saveWebPartChanges();
                    clientContext.executeQueryAsync(function (sender, args) {
                        SP.UI.Notify.addNotification("Operation completed successfully.", false, "", null);
                    }, this.onClientQueryFailed);

                });
            },

            onWebPartAddCompleted: function (zoneId, zoneSelector) {
                try {
                    var pageUrl = '/Pages/home.aspx' /*WPSC.WebPartPage.WebURL*/;

                    /* __doPostBack(); */
                    iSharePoint.WebPartManager.doDestroy();
                    $(zoneSelector + " > table").load(pageUrl + " " + zoneSelector + " > table > tbody", function () {
                        iSharePoint.WebPartManager.doInit();
                        $("tr", $(zoneSelector + " tbody"))
							.find(".ms-WPHeader")
							.css({ cursor: 'move' });
                        $(zoneSelector).unblock();
                    });
                }
                catch (ex) {
                    SP.UI.Notify.addNotification("Operation was cancelled...", false, "", null);
                }
            },

            onClientQueryFailed: function (sender, args) {
                SP.UI.Notify.addNotification("Operation was cancelled...", false, "", null);
            }
        }
    })();

    iSharePoint.WebPartManager.createSortableSettings = function () {
        return {
            handle: '.ms-WPHeader',
            forcePlaceholderSize: false,
            placeholder: 'widget-placeholder',
            revert: 300,
            distance: 5,
            helper: function (e, ui) {
                ui.children().each(function () {
                    $(this).width($(this).width());
                });
                return ui;
            },
            start: function (e, ui) {
                $(ui.helper).addClass('dragging');
                ui.placeholder.html('<!--[if IE]><td class="s4-wpcell-plain"><div style="height:' + ($(ui.helper).height() - 25).toString() + 'px">&nbsp;</div></td><![endif]-->');
            },
            update: function (e, ui) {
                var zoneIndex = $(this).children().index(ui.item[0]);
                var zoneId = ui.item.parent().parent().parent().attr('zoneId');

                if (ui.item.hasClass('mis-wpg-wpTile')) { // Adding new WebPart to Zone
                    ui.item     /* TR */
                  .parent() /* TBODY */
                  .parent() /* TABLE */
                  .parent() /* DIV */
                  .block({
                      overlayCSS: { opacity: 0.7, filter: 'alpha(opacity=70)', backgroundColor: '#182738' },
                      message: 'updating...',
                      css: { border: 'none', padding: '15px', backgroundColor: '#000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .5, color: '#fff' }
                  });

                    var wpdef = ui.item.find('div.mis-gallery-web-part').attr('wpdef');
                    iSharePoint.WebPartManager.addWebPart("div.mis-wpZone[zoneId='" + zoneId + "']", wpdef, zoneId, zoneIndex);

                    $(ui.item).find('div[id]').removeClass('draggable');

                } else { // Change ZoneIndex for WebPart

                    var webPartId = $("div.ms-WPBody", ui.item).attr("WebPartID");
                    iSharePoint.WebPartManager.moveWebPart("div.mis-wpZone[zoneId='" + zoneId + "'] > TABLE > TBODY", webPartId, zoneId, zoneIndex);
                }
            },
            stop: function (e, ui) {
                $(ui.item).removeClass('dragging');
            }
        }
    };